package com.example.courseapp.ui.login

import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import android.util.Patterns
import com.example.courseapp.data.LoginRepository
import com.example.courseapp.data.Result

import com.example.courseapp.R

/**
 * 登陆验证
 */
class LoginViewModel(private val loginRepository: LoginRepository) : ViewModel() {

    private val _loginForm = MutableLiveData<LoginFormState>()
    val loginFormState: LiveData<LoginFormState> = _loginForm

    private val _loginResult = MutableLiveData<LoginResult>()
    val loginResult: LiveData<LoginResult> = _loginResult

    /**
     *  账号密码登陆，调用loginRepository的登陆方法，通过状态验证是否登陆
     */
    fun login(context: Context, username: String, password: String) {
        // can be launched in a separate asynchronous job
        val result = loginRepository.login(context,username, password)

        if (result is Result.Success) {
            _loginResult.value =
                LoginResult(success = LoggedInUserView(displayName = result.data.displayName))
        } else {
            _loginResult.value = LoginResult(error = R.string.login_failed)
        }
    }

    /***
     * 输入内容 发生变化通过loginFormState验证状态
     */
    fun loginDataChanged(username: String, password: String) {
        if (!isUserNameValid(username,loginRepository)) {
            _loginForm.value = LoginFormState(usernameError = R.string.invalid_username)
        } else if (!isPasswordValid(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.invalid_password)
        } else {
            _loginForm.value = LoginFormState(isDataValid = true)
        }
    }

    /**
     * 验证用户名是否在登陆列表中
     */
    // A placeholder username validation check
    private fun isUserNameValid(username: String, loginRe:LoginRepository): Boolean {
        val loginData =loginRe.dataSource
        return if (loginData.userMap.contains(username)==false) {
            //Patterns.EMAIL_ADDRESS.matcher(username).matches
            _loginForm.value = LoginFormState(usernameError = R.string.no_username)
            username.contains(username)
        } else {
            //观察 username
            Log.d("username","$username")
            username.isNotBlank()
        }
    }

    /**
     * 验证邮箱是否初始化
     */
    private fun isMailValid(username: String): Boolean {
        return if (username.contains('@')) {
            Patterns.EMAIL_ADDRESS.matcher(username).matches()
        } else {
            username.isNotBlank()
        }
    }

    /**
     * 设置密码必须大于5
     */
    // A placeholder password validation check
    private fun isPasswordValid(password: String): Boolean {
        return password.length > 5
    }
}